from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 1. 打开浏览器
driver = webdriver.Chrome()
driver.maximize_window()

# 2. 访问页面
url = r"C:\Users\yh\PycharmProjects\UI自动化\注册实例.html"
driver.get(url)

# 保存主窗口句柄
main_window = driver.current_window_handle


# 1). 填写主页面的注册信息
WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.CSS_SELECTOR, "#user"))
).send_keys("admin")

driver.find_element_by_css_selector("#password").send_keys("123456")
driver.find_element_by_css_selector("#tel").send_keys("13012345678")
driver.find_element_by_css_selector("#email").send_keys("123@qq.com")


# 点击'注册A页面'链接（打开新窗口）
driver.find_element_by_partial_link_text("A网页").click()
sleep(1)  # 等待新窗口打开

# 切换到新窗口
# window_handles 是按窗口打开顺序排列的列表，[-1] 表示最后打开的窗口
driver.switch_to.window(driver.window_handles[-1])


# 2). 填写注册页面A中的信息
WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.CSS_SELECTOR, "#userA"))
).send_keys("1111")

driver.find_element_by_css_selector("#passwordA").send_keys("123456")
driver.find_element_by_css_selector("#telA").send_keys("13012345678")
driver.find_element_by_css_selector("#emailA").send_keys("123@qq.com")


# # 操作注册页面B：
# # 点击打开B页面的链接
# driver.find_element_by_partial_link_text("B网页").click()
# sleep(1)
# # 切换到B页面（此时最后打开的窗口是B，直接取[-1]）
# driver.switch_to.window(driver.window_handles[-1])
# # 操作B页面元素（示例）
# WebDriverWait(driver, 10).until(
#     EC.visibility_of_element_located((By.CSS_SELECTOR, "#userB"))
# ).send_keys("2222")


# 停留3秒观察
sleep(3)

# 关闭所有窗口
driver.quit()